package cn.ecut.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @Author ruanxin
 */
public class FileServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断上传的表单是普通表单还是带文件的表单
        if (!ServletFileUpload.isMultipartContent(req)) {
            return;//终止方法运行，说明这是一个普通表单，直接返回
        }

        //创建上传文件存放路径，建议在WEB-INF下，安全用户无法直接访问上传的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();//创建这个目录
        }

        //缓存，临时文件
        //临时路径，如果文件超过了预期的大小，我们就把他放到个临时文件中，过几天自动删除，或者提醒用户转存为永久
        String tem = this.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(tem);
        if (!file.exists()) {
            file.mkdir();//创建这个目录
        }

        //处理上传的文件，一般都需要通过流来实现，我们可以使用request.getInputStream()，原生态的文件上传流实现，十分麻烦
        //但是我们都建议使用Apache的文件上传组件实现，common-fileupload，它需要依赖commons-io组件

        /*
            ServletFileUpload负责处理上传的文件数据，并将表单中的每个输出项封装成一个FileItem对象，
            在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象
            所以我们需要在进行解析工作前构造好DiskFileItemFactory对象
            通过ServletFileUpload对象的构造方法
            或者setFileItemFactory()方法设置ServletFileUpload对象的fileItemFactory属性
        */

        try {
            DiskFileItemFactory factory = getDiskFileItemFactory(file);
            System.out.println("getDiskFileItemFactory success");
            ServletFileUpload upload = getServletFileUpload(factory);
            System.out.println("getServletFileUpload success");
            String msg = uploadParseRequset(upload, req, uploadPath);
            if("文件上传成功".equals(msg)){
                System.out.println("文件上传成功");
            }else {
                System.out.println("文件上传失败");
            }


            req.setAttribute("msg",msg);
            req.getRequestDispatcher("info.jsp").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        return upload;
    }

    public String uploadParseRequset(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws Exception {
        List<FileItem> fileItems = upload.parseRequest(request);
        String msg = "失败";

        for (FileItem fileItem : fileItems) {
            //判断上传的文件是普通表单还是带文件的表单
            if (fileItem.isFormField()) {
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8");//处理乱码
                System.out.println(name + ":" + value);
            } else {//文件

                //---------------------处理文件-----------------------//
                String uploadFileName = fileItem.getName();
                System.out.println("uploadFileName:"+uploadFileName);
                //可能存在文件名不合法的情况
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }
                //获得上传的文件名/imag/01/aaa.png
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                //获得文件后缀名
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                //可以使用UUID（唯一识别通用码），保证文件名唯一
                //UUID.randomUUID()，随机生成一个唯一识别通用码

                //网络传输的东西，都需要序列化
                //POJO 实体类，如果想在多个电脑上运行，传输+++>需要把对象都序列化
                //JNI = Java Native Interface
                //implements Serializable :标记接口，JVM---> Java栈 本地方法栈 native --->c++

                String uuidPath = UUID.randomUUID().toString();

                //---------------------存放地址-----------------------//
                //存到哪？uploadPath
                //文件真实存在路径realPath
                String realPath = uploadPath + "/" + uuidPath;
                File realPathFile = new File(realPath);
                System.out.println("realPath:"+realPath);
                //给每个文件创建一个对应的文件夹
                if (!realPathFile.exists()) {
                    realPathFile.mkdir();
                }

                //---------------------文件传输-----------------------//
                //获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();

                //创建一个文件输出流
                //realPath=真实的文件夹
                //差一个文件，加上输出的文件名字+ "/" + uuidName
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                //创建一个缓冲区
                byte[] buffer = new byte[1024 * 1024];

                //判断读取是否完毕
                int len = 0;
                //如果大于0说明还存在数据
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                //关闭流
                fos.close();
                inputStream.close();

                msg = "文件上传成功";
                fileItem.delete();//上传成功删除临时文件

            }
        }
        return msg;
    }

}
